package il.technion.cs236369.webserver.simpleServlets;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

/**
 * @author Sabre Runner
 *
 */
public class UserDistanceServlet implements HttpRequestHandler
{
	private final String xhtmlHeader = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""+
			"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
			"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
	private final String endl = System.getProperty("line.separator");

	public UserDistanceServlet()
	{
		
	}

	private String[] GetCoors(HttpContext context)
	{
		ArrayList<String> tempResult = new ArrayList<String>(); 
		String value = ""; 
		int index = 0;
		
		do
		{
			value = (String)context.getAttribute("coors" + String.valueOf(index));
			if (value != null)
			{
				tempResult.add(value);
			}
			index++;
		} while (value != null);
		
		String[] result = new String[tempResult.size()];
		for (int i = 0; i < tempResult.size(); i++)
		{
			result[i] = tempResult.get(i); 
		}
		
		return result;
	}
	
	private int[] CoorsStringToCoors(String coorsString)
	{
		int[] coors = new int[2];
		String[] latLong = coorsString.split("&");
		coors[0] = Integer.parseInt(latLong[0]);
		coors[1] = Integer.parseInt(latLong[1]);
		return coors;
	}
	
	private double DistanceBetweenCoors(int[] coors1, int[] coors2)
	{
		double a = coors1[0] - coors2[0];
		double b = coors1[1] - coors2[1];
		return Math.sqrt(a*a + b*b);
	}
	
	/**
	 * What this servlet should do on a post request
	 * @param request
	 * @param context should contain user name and coordinates
	 * @return a string builder with the contents of the page (no enclosing tags)
	 */
	private StringBuilder HandlePost(HttpRequest request, HttpContext context)
	{
		//String[] coors = GetCoors(context);
		
		return new StringBuilder("Coordinates logged." + endl)
					.append("<FORM><INPUT Type=\"button\" VALUE=\"Back\" ")
					.append("onClick=\"history.go(-1);return true;\"></FORM>" + endl);
	}

	/**
	 * What this servlet should do on a get request
	 * @param request
	 * @param context should contain user name and coordinates
	 * @return a string builder with the contents of the page (no enclosing tags)
	 */
	private StringBuilder HandleGet(HttpRequest request, HttpContext context)
	{
		// grab coordinates strings from context
		String[] coorsStrings = GetCoors(context);
		
		// convert to actual numbers
		int[][] coors = new int[coorsStrings.length][];
		for (int index = 0; index < coorsStrings.length; index++)
		{
			coors[index] = CoorsStringToCoors(coorsStrings[index]);
		}
		
		// Calculate maximum distance
		double maxDistance = 0;
		for (int index1 = 0; index1 < coorsStrings.length; index1++)
		{
			for (int index2 = index1 + 1 ; index2 < coorsStrings.length; index2++)
			{
				double distance = DistanceBetweenCoors(coors[index1], coors[index2]);
				if (distance > maxDistance)
				{
					maxDistance = distance;
				}
			}
		}
		
//		return new StringBuilder("Maximum Distance between all coordinates logged so far is: ")
//					.append(maxDistance).append(endl)
//					.append("<FORM><INPUT Type=\"button\" VALUE=\"Back\" ")
//					.append("onClick=\"history.go(-1);return true;\"></FORM>" + endl);
		return new StringBuilder(Double.valueOf(maxDistance).toString());
	}

	@Override
	public void handle(HttpRequest request, HttpResponse response, HttpContext context)
						throws HttpException, IOException
	{
		// start building the page
		StringBuilder page = new StringBuilder();
		page.append(BuildPageTitle("User Distance Servlet")).append("<body>" + endl);

		switch (request.getRequestLine().getMethod().toLowerCase())
		{
			case "get":
				page.append(HandleGet(request, context));
				break;
			case "post":
				page.append(HandlePost(request, context));
				break;
			default:
				page.append("I don't know what you did but you probably broke the internet.<br>" +
							"Go home and think about what you did.");
		}
		
		page.append(endl + "</body>" + endl + "</html>" + endl);
		// send it away
		StringEntity pageEntity = new StringEntity(page.toString(), "UTF-8");
		response.setEntity(pageEntity);
	}

	/**
	 * Returns an html head with included title
	 * @param title the title of the page
	 * @return an html head including opening html tag,
	 * 		opening and closing head and title tags<br>
	 * 		still need to add body and closing html tags
	 */
	private String BuildPageTitle(String title)
	{
		return xhtmlHeader + "\t<head>" + endl + "\t\t<title>" + title +
				"</title>" + endl + "\t</head>" + endl + endl;
	}
	
}
